package com.pipe.protocol.events.table.reader;

import com.pipe.exception.ColumnReaderException;
import com.pipe.util.IntegerConveter;
import com.pipe.util.MyBytebufUtil;
import io.netty.buffer.ByteBuf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author Kiven
 * @see <a>https://dev.mysql.com/doc/internals/en/date-and-time-data-type-representation.html</a>
 */
public class MysqlTypeDatetime2Reader implements ColumnReader<String>{
    private Logger log = LoggerFactory.getLogger(MysqlTypeDatetime2Reader.class);

    @Override
    public String read(ByteBuf byteBuf, int readLength) throws ColumnReaderException {
        log.debug("parse datetime!");
        byte[] dateArr = new byte[5];
        byteBuf.readBytes(dateArr);
        return decodeDateTime(dateArr);
    }

    private String decodeDateTime(byte[] bytes) throws ColumnReaderException {
        byte[] bitData = IntegerConveter.getBitArrayFromByteArr(bytes);
        /**(1= non-negative, 0= negative)*/
        if (bitData[0] == 1){
            return doNonNegativeParse(bitData);
        }
        throw new ColumnReaderException("Unsupported type of [negative]");
    }

    private String doNonNegativeParse(byte[] sourceBytes){
        byte[] yearAndMonth = new byte[17];
        System.arraycopy(sourceBytes, 1, yearAndMonth, 0, 17);
        long ym = IntegerConveter.getLongFromBitArr(yearAndMonth);
        long year = ym / 13;
        int month = (int) (ym % 13);

        byte[] day = new byte[5];
        System.arraycopy(sourceBytes, 1 + 17, day, 0, 5);
        long d = IntegerConveter.getLongFromBitArr(day);

        byte[] hour = new byte[5];
        System.arraycopy(sourceBytes, 1 + 17 + 5, hour, 0, 5);
        long h = IntegerConveter.getLongFromBitArr(hour);

        byte[] minute = new byte[6];
        System.arraycopy(sourceBytes, 1 + 17 + 5 + 5, minute, 0, 6);
        long m = IntegerConveter.getLongFromBitArr(minute);

        byte[] second = new byte[6];
        System.arraycopy(sourceBytes,  1 + 17 + 5 + 5 + 6, second, 0, 6);
        long s = IntegerConveter.getLongFromBitArr(second);

        StringBuilder dateTime = new StringBuilder();
        dateTime.append(year).append("-").append(month).append("-").append(d).append(" ").append(h).append(":").append(m).append(":").append(s);
        return dateTime.toString();
    }
}